﻿using Cms.Application.Admin.Views;
using Cms.Data;
using Cms.Domain;
using Cms.Domain.RepositoryInterfaces;

namespace Cms.Application.Admin.Presenters
{
    public class EditMembershipPresenter : BasePresenter
    {
        private readonly Administrator _administrator;
        private readonly IEditMembershipView _view;

        public EditMembershipPresenter(IEditMembershipView view)
            : this(view, new RepositoryFactory())
        {
        }

        public EditMembershipPresenter(IEditMembershipView view, IRepositoryFactory repositoryFactory)
            : base(view, repositoryFactory)
        {
            _view = view;
            _administrator = AdministratorRepository.GetAdministrator(_view.AdministratorID);
            //if (!_administrator.HasPermission.EditMembership)
            //    _view.RedirectToPermissionDeniedPage();
        }

        public void Initialize()
        {
            _view.SetUserGroups(UserRepository.GetUserGroups());
            if (_view.MembershipID == -1)
            {
            }
            else
            {
                User user = UserRepository.GetUser(_view.UserID);
                Domain.Membership membership = user.GetMembership(_view.MembershipID);
                if (membership == null)
                {
                    return;
                }
                _view.StartDate = membership.StartDate;
                _view.EndDate = membership.EndDate;
            }
        }

        public void Save()
        {
            User user = UserRepository.GetUser(_view.UserID);
            Domain.Membership membership = user.GetMembership(_view.MembershipID);
            if (membership == null)
            {
                membership = new Membership();
                user.Memberships.Add(membership);
                membership.User = user;
            }
            membership.UserGroup = UserRepository.GetUserGroup(_view.SelectedUserGroupID);
            membership.StartDate = _view.StartDate;
            membership.EndDate = _view.EndDate;
            UserRepository.SaveUser(user);
        }
    }
}